package com.it.jzs.service.impl;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.it.jzs.dao.UserMapper;
import com.it.jzs.dao.admin.AdminUserMapper;
import com.it.jzs.pojo.User;
import com.it.jzs.service.UserService;
import com.it.jzs.vo.Result;
import com.it.jzs.vo.params.LoginParams;
import com.it.jzs.vo.params.RegisterParams;
import com.it.jzs.vo.params.UserUpdateParams;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Service
public class UserServiceImpl implements UserService {

    private final String SLOT = "jzs";   // MD5加盐

    private final String NO_UPDATE = "1";  //1表示 没有执行修改密码的操作

    @Resource
    private AdminUserMapper userMapper;

    @Override
    public Result<Object> register(RegisterParams registerParams) {
        String username = registerParams.getUsername();
//        StringUtils.isEmpty()
        String password1 = registerParams.getPassword();
        String nickname = registerParams.getNickname();
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password1) || StringUtils.isEmpty(nickname)) {
            return Result.error(null, "数据不合法");
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();

        wrapper.eq("username", username).or().eq("nickname", nickname);
        User user = userMapper.selectOne(wrapper);
        if (user != null) {
            return Result.error(null, "账号或昵称已被注册");
        }
        String password = SecureUtil.md5(password1 + SLOT);
        user = new User();
        user.setType(0); // 游客
        user.setRemark("学生");
        user.setPassword(password);
        user.setCreateTime(System.currentTimeMillis());
        user.setUpdateTime(System.currentTimeMillis());
        user.setLocation("浙江杭州");
        user.setUsername(username);
        user.setNickname(nickname);
        int insert = userMapper.insert(user);
        if (insert > 0) {
            return Result.success(null, "注册成功");
        }
        return Result.error(null, "注册失败");
    }

    @Override
    public Result<Object> login(LoginParams loginParams, HttpServletRequest request) {
        String username = loginParams.getUsername();
        String password = loginParams.getPassword();
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return Result.error(null, "数据不合法");
        }
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        String password1 = SecureUtil.md5(password + SLOT);
        wrapper.eq("username", username).eq("password", password1);
        User user = userMapper.selectOne(wrapper);
        if (user != null) {
            // 密钥
            byte[] key = SLOT.getBytes();
            String token = JWT.create()
                    .setPayload("type", user.getType())  // 这里的type 加了空格不小心
                    .setPayload("nickname", user.getNickname())
                    .setPayload("id", user.getId())
                    .setPayload("avatar", user.getAvatar())
                    .setPayload("username", user.getUsername())
                    .setPayload("location", user.getLocation())
                    .setPayload("remark", user.getRemark())
                    .setKey(key)
                    .sign();
            HttpSession session = request.getSession();
            session.setAttribute("id", token);
            return Result.success(token, "登录成功！");
        }
        return Result.error(null, "账号或密码不正确");
    }

    @Override
    public Result<Object> update(UserUpdateParams updateParams) {
        Integer id = updateParams.getId();
        String location = updateParams.getLocation();
        String password = updateParams.getPassword();
        String remark = updateParams.getRemark();
        String passwordMD5 = null;
//        updateParams.
        if (StringUtils.isEmpty(id) || StringUtils.isEmpty(location) || StringUtils.isEmpty(remark)) {
            return Result.error(null, "数据不合法");
        }
//        根据用户id查出来密码，和当前前端查出来的密码进行比较，如果相同或者密码为null 就说明没有修改密码
        if (password != null) {
            passwordMD5 = SecureUtil.md5(password + SLOT);
        }
//        boolean flag = false;
        updateParams.setPassword(passwordMD5);
        User user = new User();
        BeanUtils.copyProperties(updateParams, user); // 进行对象值的拷贝
        user.setUpdateTime(System.currentTimeMillis());
        int i = userMapper.updateById(user);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);

        User user1 = userMapper.selectOne(wrapper);
        if (i > 0) {  // 修改成功并且没有修改密码，那么前端就不需要消除token
            // 密钥
            byte[] key = SLOT.getBytes();
            String token = JWT.create()
                    .setPayload("type ", user1.getType())
                    .setPayload("nickname", user1.getNickname())
                    .setPayload("id", user1.getId())
                    .setPayload("avatar", user1.getAvatar())
                    .setPayload("username", user1.getUsername())
                    .setPayload("location", user1.getLocation())
                    .setPayload("remark", user1.getRemark())
                    .setKey(key)
                    .sign();
            return Result.success(token, "修改成功");
        }
        return Result.error(null, "修改失败");
    }
}
